package helper

import (
	"github.com/sirupsen/logrus"
	"io"
	"os"
	"strconv"
	"strings"
	"time"
)

type logHook struct {
	Appname string
}

var LogFileName string
var logPath, lastLogFile string
var year, month, day int

func InitLogger() {
	logSettings := Configer.GetStringMapString("log")
	driver := logSettings["driver"]

	if strings.Contains(driver, "file") {
		y, m, d := time.Now().Date()
		year, month, day = y, int(m), d

		getLogPath(logSettings["path"])

		/* 创建日志目录 start */
		logFileInfo := strings.Split(logSettings["filename"], ".")
		LogFileName = logPath + logFileInfo[0] + "-" + strconv.Itoa(day) + "." + logFileInfo[1]
		if err := MkDir(logPath); err != nil {
			panic(err.Error())
		}
		/* 创建日志目录 end */
	}

	logger := logrus.New()
	// 输入调用函数及文件
	logger.SetReportCaller(true)
	// 设置日志级别
	levelMap := map[string]logrus.Level{
		"panic": logrus.PanicLevel,
		"fatal": logrus.FatalLevel,
		"error": logrus.ErrorLevel,
		"warn":  logrus.WarnLevel,
		"info":  logrus.InfoLevel,
		"debug": logrus.DebugLevel,
		"trace": logrus.TraceLevel,
	}
	runmode := Configer.GetString("runmode")
	if "product" == runmode {
		logger.SetLevel(levelMap[logSettings["product_level"]])
		logger.SetFormatter(&logrus.JSONFormatter{})
	} else {
		logger.SetLevel(levelMap[logSettings["dev_level"]])
		logger.SetFormatter(&logrus.TextFormatter{})
	}
	// 设置日志输出
	setOutPut(LogFileName, logger)
	// 添加日志钩子
	h := &logHook{Appname: Configer.GetString("appname")}
	logger.AddHook(h)

	Logger = logger

}

func getLogPath(basePath string) {
	logPath = strings.TrimRight(basePath, "/")
	monthStr := strconv.Itoa(month)
	if month < 10 {
		monthStr = "0" + monthStr
	}
	logPath = logPath + "/" + strconv.Itoa(year) + monthStr + "/"
}

func setOutPut(file string, logger *logrus.Logger) {
	var isFile, isStd bool
	logSettings := Configer.GetStringMapString("log")
	if strings.Contains(logSettings["driver"], "file") {
		isFile = true
	}
	if strings.Contains(logSettings["driver"], "console") {
		isStd = true
	}
	if isFile && isStd {
		var wFile *os.File
		if file, err := os.OpenFile(file, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0664); err != nil {
			panic(err.Error())
		} else {
			wFile = file
		}
		logger.SetOutput(io.MultiWriter(wFile, os.Stdout))
	} else if isFile {
		var wFile *os.File
		if file, err := os.OpenFile(file, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0664); err != nil {
			panic(err.Error())
		} else {
			wFile = file
		}
		logger.SetOutput(io.MultiWriter(wFile))
	} else if isStd {
		logger.SetOutput(os.Stdout)
	} else {
		logger.SetOutput(os.Stdout)
	}
	lastLogFile = file
}

/* 日志钩子 */
func (h *logHook) Levels() []logrus.Level {
	return logrus.AllLevels
}

func (h *logHook) Fire(entry *logrus.Entry) error {
	y, m, d := time.Now().Date()
	if y != year || int(m) != month || d != day {
		InitLogger()
	}
	entry.Data["appname"] = h.Appname
	if val, ok := entry.Data["apart"]; ok {
		// 设置独立日志级别
		logFile := logPath + val.(string) + "-" + strconv.Itoa(d) + ".log"
		if logFile != lastLogFile {
			setOutPut(logFile, entry.Logger)
		}
	} else {
		if LogFileName != lastLogFile {
			setOutPut(LogFileName, Logger)
		}
	}
	return nil
}

/* 日志钩子 */
